package com.synjones.handsetS8.PictureFaceMatch;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.PictureFaceMatch.camare.CameraPreview;
import com.synjones.handsetS8.PictureFaceMatch.camare.FocusView;
import com.synjones.handsetS8.facesdk.FaceHandle;
import com.synjones.handsetS8.facesdk.IFaceSDK;
import com.synjones.handsetS8.ild.net.api.HandSetApi;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class TakePhotoActivity extends Activity implements CameraPreview.OnCameraStatusListener,
        SensorEventListener {
    private static final String TAG = "TakePhoteActivity";
    CameraPreview mCameraPreview;
    RelativeLayout mTakePhotoLayout;
    LinearLayout mCropperLayout;
    public static byte img[];
    TextView hint_tv;
    Bitmap idcardPhoto;
    Bitmap presentPhoto;

    ImageView ivIdcardPhoto;
    ImageView ivPresentPhoto;
    final static float VERIFY_THRESHOLD = 75;
    SoundPool soundPool;
    IFaceSDK iFaceSDK;
    private Object idcardPhotofeaObj;
    //用于存放当前核验的身份证信息
    private Map<String, Object> idCardInfo;
    private boolean check = false;//核验是否成功

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_take_photo);
        mCameraPreview = (CameraPreview) findViewById(R.id.cameraPreview);
        FocusView focusView = (FocusView) findViewById(R.id.view_focus);
        mTakePhotoLayout = (RelativeLayout) findViewById(R.id.take_photo_layout);
        mCropperLayout = (LinearLayout) findViewById(R.id.cropper_layout);
        ivIdcardPhoto = (ImageView) findViewById(R.id.ivIdcardPhoto);
        ivPresentPhoto = (ImageView) findViewById(R.id.ivPresentPhoto);
        mCameraPreview.setFocusView(focusView);
        mCameraPreview.setOnCameraStatusListener(this);
        mSensorManager = (SensorManager) getSystemService(Context.
                SENSOR_SERVICE);
        mAccel = mSensorManager.getDefaultSensor(Sensor.
                TYPE_ACCELEROMETER);

        hint_tv = (TextView) findViewById(R.id.hint);
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, R.raw.hycg, 1);
        soundPool.load(this, R.raw.hysb, 1);

        //读取页面跳转传递的数据
        Intent intent = getIntent();
        byte[] imgBytes = intent.getByteArrayExtra("img_byte");
        int ALGORITHM_VERSION = intent.getIntExtra("ALGORITHM_VERSION", 2);
        String idCardInfoJson = intent.getStringExtra("ID_CARD_INFO");
        if (null != idCardInfoJson && !"".equals(idCardInfoJson.trim())) {
            this.idCardInfo = new Gson().fromJson(idCardInfoJson, HashMap.class);
        }


        iFaceSDK = FaceHandle.getFaceSDKInstance(ALGORITHM_VERSION);
        if (img != null) {
            idcardPhoto = BitmapFactory.decodeByteArray(img, 0, img.length);
            ivIdcardPhoto.setImageBitmap(idcardPhoto);
            hint_tv.setText("请对准人脸拍照核验");
            idcardPhotofeaObj = null;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    idcardPhotofeaObj = iFaceSDK.getIDCardPhotoFeature(idcardPhoto);
                }
            }).start();

        }

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onDestroy() {
        soundPool.release();
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.e(TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }

    public void takePhoto(View view) {
        if (mCameraPreview != null) {
            mCameraPreview.takePicture();
        }
    }

    public void openlight(View view) {
        if (mCameraPreview != null) {
            mCameraPreview.openLight();
            view.setVisibility(View.GONE);
            View v = findViewById(R.id.nolight);
            v.setVisibility(View.VISIBLE);
        }
    }

    public void offlight(View v) {
        if (mCameraPreview != null) {
            mCameraPreview.offLight();
            v.setVisibility(View.GONE);
            View view = findViewById(R.id.light);
            view.setVisibility(View.VISIBLE);
        }
    }

    public void close(View view) {
        finish();
    }


    /**
     * 拍照成功后回调
     * 存储图片并显示截图界面
     *
     * @param data
     */
    @Override
    public void onCameraStopped(byte[] data) {
        Log.i("TAG", "==onCameraStopped==");
        new VerifyAsyncTask(data).execute();
    }

    private class VerifyAsyncTask extends AsyncTask<Void, Void, Integer> {
        byte[] data;
        private ProgressDialog dialog = null;

        public VerifyAsyncTask(byte[] data) {
            this.data = data;
        }

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(TakePhotoActivity.this, "", "正在核验，请稍等", true);
            super.onPreExecute();
            presentPhoto = BitmapFactory.decodeByteArray(data, 0, data.length);//getBitmapFromData(data);
            ivPresentPhoto.setImageBitmap(presentPhoto);
        }

        @Override
        protected Integer doInBackground(Void... params) {
            if (idcardPhotofeaObj == null)
                idcardPhotofeaObj = iFaceSDK.getIDCardPhotoFeature(idcardPhoto);
            if (idcardPhotofeaObj == null) return 0;
            Object presentPhotoFeaObj = iFaceSDK.getPresentPhotoFeature(presentPhoto);
            return iFaceSDK.compareFeature(idcardPhotofeaObj, presentPhotoFeaObj);
        }

        @Override
        protected void onPostExecute(Integer score) {
            mCameraPreview.start();
            dialog.dismiss();
            checkScore(score);
            super.onPostExecute(score);
        }
    }


    private void checkScore(final int score) {
        String msg = "核验失败";
        if (score >= VERIFY_THRESHOLD) {
            check = true;
            msg = "核验成功";
            setResult(RESULT_OK);
            soundPool.play(1, 1, 1, 0, 0, 1);
        } else {
            soundPool.play(2, 1, 1, 0, 0, 1);
        }

        new AlertDialog.Builder(TakePhotoActivity.this)
                .setTitle("对比结果")
                .setMessage(msg)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!check || idCardInfo == null) {
                            Toast.makeText(TakePhotoActivity.this, String.valueOf(idCardInfo.get("name")) + " 未确认", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(TakePhotoActivity.this, String.valueOf(idCardInfo.get("name")) + " 确认", Toast.LENGTH_SHORT).show();

                            //向后端服务传数据
                            HandSetApi.addIdCard(idCardInfo, callback);
                            TakePhotoActivity.this.finish();
                        }
                    }
                }).setCancelable(false).show();
    }

    /**
     * 发送身份证信息的网络请求回调
     */
    Callback<ResponseBody> callback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            System.out.println(response.body());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            System.out.println("请求失败");
        }
    };


    private float mLastX = 0;
    private float mLastY = 0;
    private float mLastZ = 0;
    private boolean mInitialized = false;
    private SensorManager mSensorManager;
    private Sensor mAccel;

    @Override
    public void onSensorChanged(SensorEvent event) {

        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized) {
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        }
        float deltaX = Math.abs(mLastX - x);
        float deltaY = Math.abs(mLastY - y);
        float deltaZ = Math.abs(mLastZ - z);

        if (deltaX > 0.8 || deltaY > 0.8 || deltaZ > 0.8) {
            mCameraPreview.setFocus();
        }
        mLastX = x;
        mLastY = y;
        mLastZ = z;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}